package br.com.maps.util.report;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Utilit�rio para clonar objetos (somente Serializaveis)
 * 
 * @author takeshi
 */
public final class ObjectCloner {

    /**
     * C'tor
     */
    private ObjectCloner() {
    }

    /**
     * Clona o objeto dado. Ele deve ser Serializavel
     * 
     * @param e Objeto a ser clonado
     * @param <E> Tipo
     * @return Objeto clonado
     * @throws NotSerializableException Se ocorrer
     */
    @SuppressWarnings("unchecked")
    public static <E> E hardClone(final E e) throws NotSerializableException {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream objOut = new ObjectOutputStream(bout);
            objOut.writeObject(e);
            objOut.flush();
            objOut.close();
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            ObjectInputStream ibjin = new ObjectInputStream(bin);
            return (E) ibjin.readObject();
        } catch (NotSerializableException e1) {
            // rethrow
            throw e1;
        } catch (ClassNotFoundException e1) {
            throw new ExceptionInInitializerError("BUG! Classloader n�o achou a classe!");
        } catch (IOException ioe) {
            throw new ExceptionInInitializerError("BUG! Classloader n�o achou a classe!");
        }
    }
}
